package com.amado.course45mysql03.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.amado.course45mysql03.dao.RoleDao;
import com.amado.course45mysql03.domain.Role;
import com.amado.course45mysql03.vo.Page;

public class RoleDaoImpl implements RoleDao{

	@Override
	public boolean add(Role t) {
		Connection conn = DBConnection.getConn(); 
		String sql = "insert into t_role(role_code,role_name)values(?,?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, t.getRoleCode());
			ps.setString(2, t.getRoleName());
			ps.execute();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBConnection.close(null, ps, conn);
		}
		return false;
	}

	@Override
	public boolean upadte(Role t) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isExists(String roleCode) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean delete(String roleCode) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Role getByCode(String roleCode) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Role> listAll() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public int getCount(){
		Connection conn = DBConnection.getConn(); 
		String sql = "select count(1) from t_role";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			rs.next();
			return rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBConnection.close(null, ps, conn);
		}
		return 0;
	}
	@Override
	public List<Role> listAll(Page<Role> page) {
		Connection conn = DBConnection.getConn(); 
		String sql = "select id,role_code,role_name,create_time from t_role limit ?,?";
		PreparedStatement ps = null;
		List<Role> roleList = new ArrayList();
		try {
			ps = conn.prepareStatement(sql);
			//0,5  (1-1)*5,5
			//5,5  (2-1)*5,5
			//10,5 (3-1)*5,5
			ps.setInt(1, (page.getCurrentPage()-1)*page.getPageSize());
			ps.setInt(2, page.getPageSize());
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				Role role = new Role(rs.getLong(1),rs.getString(2),rs.getString(3),rs.getDate(4));
				roleList.add(role);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBConnection.close(null, ps, conn);
		}
		return roleList;
	}
	
}
